#include "scene/rightmousecontroller.h"
#include "wsyperspectivecamera.h"
#include "wsymath/wsymath.h"

/** 鼠标按下的事件 */
void RightMouseController::mousePressEvent(QMouseEvent *event){
    initX = event->x(); initY = event->y();
    WSYPerspectiveCamera *camera = (WSYPerspectiveCamera *)scene->getCamera();

    cPosition = camera->getPosition()->clone();
    cLookAt = camera->getLookAt()->clone();

    Vector3D *cameraLookAtDirection
            = Math3D::direction(cPosition, cLookAt);
    Vector3D *nCameraLookAtDirection = cameraLookAtDirection->normalize();

    xDirection = Math3D::crossVectors(cameraLookAtDirection, camera->getUpright())->normalize();
    yDirection = Math3D::crossVectors(xDirection, cameraLookAtDirection)->normalize();
    mousePressed = true;
}

/** 鼠标移动的事件 */
void RightMouseController::mouseMoveEvent(QMouseEvent *event){
    if (mousePressed) {
        int XGap = event->x() - initX, YGap = initY - event->y();
        XGap = -XGap; YGap = -YGap;


        WSYPerspectiveCamera *camera = (WSYPerspectiveCamera *)scene->getCamera();
        double positionLookAtLength = Math3D::direction(cPosition, cLookAt)->length();

        double allHeight = positionLookAtLength
                * tan(WSYMath::DegreeToRadian(camera->getFOV() / 2)) * 2;
        double allWidth = allHeight * widget->width() / widget->height();

        double mX = (double)XGap / widget->width() * allWidth;
        double mY = (double)YGap / widget->height() * allHeight;

        qDebug() << "mX:" << mX;
        qDebug() << "mY:" << mY;


        Vector3D *xNew = xDirection->multiply(mX);
        Vector3D *yNew = yDirection->multiply(mY);
        Vertex3D *nPosition = cPosition->addVectors(xNew)->addVectors(yNew);
        Vertex3D *nLookAt = cLookAt->addVectors(xNew)->addVectors(yNew);

        camera->setPosition(nPosition->getX(), nPosition->getY(), nPosition->getZ());
        camera->setLookAt(nLookAt->getX(), nLookAt->getY(), nLookAt->getZ());

        delete nPosition; delete nLookAt;
    }
}

/** 鼠标松开的事件 */
void RightMouseController::mouseReleaseEvent(QMouseEvent *event){
    mousePressed = false;
}
